﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using AppFramework.Logger;
using PerpheralDevice.Units;

namespace PerpheralDevice.LeadShine;
public class DMC5410A : PerpDevIO {

    protected ushort _BoardNO = 0;

    protected int mfDiCount = 0;
    protected int mfDoCount = 0;
    protected int mfAxisCount = 0;
    protected string mfConfigFilePath = string.Empty;
    private readonly ILogger miLogger;
    public DMC5410A(string devID, string devName, string devParamSerialized) :base() 
    {
        this.PerpDevID = devID;
        this.PerpDevName = devName;
        this.mfConfigFilePath = $"{Directory.GetCurrentDirectory()}\\AppData\\DataFiles\\DMC5410A-{this.PerpDevID}.ini";
        this.mfAxisCount = 4;
        this.mfDiCount = 16;
        this.mfDoCount = 16;
        this.IsMocking = !this.Initialize();
        if (this.GetType() == typeof(DMC5410A)) {
            this.InitializeUnitList();
        }
    }

    protected override bool Initialize() {
        try {
            //初始化 雷赛 运动控制卡 系统
            this.IsMocking = LeadShineWapper.Init() > 0;
            //下载配置参数到 对应卡号 的运动控制卡
            if (File.Exists(mfConfigFilePath)) {
                this.IsMocking = LeadShine.LTDMC.dmc_download_configfile(this._BoardNO, mfConfigFilePath) == 0;
                if (!this.IsMocking) {
                    this.miLogger?.Warn($"{this.PerpDevID}运动控制卡初始化失败: 下载配置文件失败");
                }
            } else {
                this.miLogger?.Warn($"{this.PerpDevID}运动控制卡配置文件丢失");
            }
        } catch (Exception ex) {
            this.IsMocking = true;
            this.miLogger?.Error($"{this.PerpDevID}运动控制卡初始化失败", ex);
            return false;
        }

        return true;
    }

    protected override void InitializeUnitList() {

        this.mfPerpDevUnitList.Clear();
        for (int i = 0; i < this.mfAxisCount; i++) {
            this.mfPerpDevUnitList.Add(new DMCMotor(this, i));
        }
        for (int i = 0; i < this.mfDiCount; i++) {
            this.mfPerpDevUnitList.Add(new DMCSwitchRO(this, i));
        }
        for (int i = 0; i < this.mfDiCount; i++) {
            this.mfPerpDevUnitList.Add(new DMCSwitchRW(this, i));
        }

        #region 轮询 IO

        this.mfPollingTask = Task.Factory.StartNew(() => {
            while (this.mfIsPolling) {
                foreach (var tempItem in this.Unit<SwitchRO>()) {
                    tempItem.View();
                }
                System.Threading.Thread.Sleep(5);
            }

        }, TaskCreationOptions.LongRunning);

        #endregion

    }

}
